package com.paipai.service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import com.github.pagehelper.PageHelper;
import com.paipai.dao.UserMapper;
import com.paipai.entity.User;
import com.paipai.utils.CodecUtils;

@Transactional
@Service
public class UserService {
	@Autowired
	private UserMapper userMapper;

	static final String KEY_PREFIX = "user:code:phone:";

	@Autowired
	private StringRedisTemplate srtle;

	public UserMapper getUserMapper() {
		return userMapper;
	}

	/**
	 * 注册查询用户名/手机号码是否重复
	 * 
	 * @param uname
	 * @return
	 */
	public Boolean unameVerify(String value, Integer type) {

		if (value == null || value.equals("") || type == null || type.equals("")) {

			return null;
		}

		// 1 验证用户名 2 验证手机号码
		String field = null;
		if (type == 1)
			field = "uname=";
		else if (type == 2)
			field = "phone=";

		// 自动拼接SQL语句
		Example exm = new Example(User.class);
		Criteria crt = exm.createCriteria();

		if (!"".equals(value)) {
			crt.andCondition(field, value);
		}
		PageHelper.startPage(0, 1);
		User user = userMapper.selectOneByExample(exm);
		return user == null ? true : false;
	}

	/**
	 * 注册
	 * 
	 * @param user
	 */

	public Integer register(User user, String code) {
		// 防重复提交 通过用户提交的用户名 密码 手机号码生成 MD5密文
		String md5Password = CodecUtils.md5Password(user.getId() + user.getPwd() + user.getPhone());

		System.out.println(md5Password);
		//redis 读取 密文
		BoundValueOperations<String, String> valueOps = srtle.boundValueOps("prevent:" + md5Password);

		// 如果redis获取 不为 null 证明提交过
		if (valueOps.get() != null) {
			return 2;
		}

		// 校验短信验证码 从redis读取
		String cacheCode = srtle.opsForValue().get(KEY_PREFIX + user.getPhone());
		if (!code.equals(cacheCode)) {
			return 0;
		}
		// 所有用户全部为买家
		user.setType(1);
		// 设置默认头像
		user.setHead("moren.jpg");

		// 生成盐
		String salt = CodecUtils.generateSalt();
		user.setSalt(salt);

		// 对密码加密
		user.setPwd(CodecUtils.md5Hex(user.getPwd(), salt));
		user.setJoinDate(new Date());
		int row = userMapper.insert(user);

		if (row == 1) {
			// 注册成功，删除 短信 redis中的记录
			this.srtle.delete(KEY_PREFIX + user.getPhone());
			// 再redis 放入放重复数据  一分钟有效
			valueOps.set("A", 1, TimeUnit.MINUTES);
		}
		return row;

	}

	/**
	 * 登录
	 * 
	 * @param user
	 * @return
	 */
	public User login(String uname, String pwd) {

		User user = new User();
		user.setUname(uname);

		// 登录 不是null就为成功
		User loginuser = userMapper.selectOne(user);

		// 校验用户名
		if (loginuser == null) {
			return null;
		}

		// 校验密码
		if (!loginuser.getPwd().equals(CodecUtils.md5Hex(pwd, loginuser.getSalt()))) {
			return null;
		}
		// 登录 不是null就为成功
		return loginuser;
	}

	/**
	 * 查询个人资料
	 * 
	 * @param uid
	 * @return
	 */

	public User findPersonalDataById(Integer uid) {

		User user = userMapper.selectByPrimaryKey(uid);
		return user;
	}

	/**
	 * 个人资料界面,上传图片
	 * 
	 * @param date
	 */
	public Integer updateUserHeadImg(Integer uid, String head) {
		User user = new User();
		user.setId(uid);
		user.setHead(head);
		return userMapper.updateByPrimaryKeySelective(user);
	}

	/**
	 * 冻结
	 * 
	 * @param id
	 * @return
	 */
	public Integer freeze(Integer id) {
		User user = new User();
		user.setId(id);
		user.setType(0);

		Integer row = userMapper.updateByPrimaryKeySelective(user);

		return row;
	}

	/**
	 * 解冻
	 * 
	 * @param id
	 * @return
	 */
	public Integer unfreeze(Integer id) {
		User user = new User();
		user.setId(id);
		user.setType(1);
		Integer row = userMapper.updateByPrimaryKeySelective(user);
		return row;
	}

	/**
	 * 验证验证码
	 * 
	 * @param authCode
	 * @param phone
	 * @return
	 */
	public Boolean authCodeVerify(String authCode, String phone) {
		// 校验短信验证码 从redis读取
		String cacheCode = srtle.opsForValue().get(KEY_PREFIX + phone);
		if (!authCode.equals(cacheCode)) {
			return false;
		}
		return true;
	}

}